package net.qhzw.vip.qiyu.component;


import net.qhzw.vip.qiyu.model.LoginForm;
import net.qhzw.vip.qiyu.util.JwtToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class JwtTokenTemplate {

    @Autowired
    private ServerConfig serverConfig;

    @Value("${basic.token:Basic Y29pbi1hcGk6Y29pbi1zZWNyZXQ=}")
    private String basicToken;

    /***
     * 发送请求登录 获取token
     * @param param
     * @return
     */
    public JwtToken sendLogin(LoginForm param, RestTemplate restTemplate) {
        String grantType = "password";
        String serverName = serverConfig.getUrl();
        String url = serverName + "/oauth/token?grant_type=%s&password=%s&username=%s&login_type=%s";
        String formatUrl = String.format(url, grantType, param.getPassword(), param.getUsername(), param.getLoginType());
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", basicToken);
        HttpEntity<String> request = new HttpEntity<>(headers);
        JwtToken jwtToken = restTemplate.postForObject(formatUrl, request, JwtToken.class);
        return jwtToken;
    }

}
